package tech.popsoft.cip.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.popsoft.cip.manage.service.ApiMessagePermissionService;
import tech.popsoft.cip.manage.service.ApiMessageTopicService;
import tech.popsoft.platform.common.base.BaseServiceImpl;
import tech.popsoft.platform.common.enums.StatusEnum;
import tech.popsoft.platform.common.enums.YesOrNoEnum;
import tech.popsoft.platform.common.exception.CommonException;
import tech.popsoft.platform.common.exception.CustomException;
import tech.popsoft.cip.manage.entity.ApiMessagePermission;
import tech.popsoft.cip.manage.entity.ApiMessageTopic;
import tech.popsoft.cip.manage.exception.ApiMessageTopicExceptionEnum;
import tech.popsoft.cip.manage.mapper.ApiMessageTopicMapper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息主题 服务实现类
 * @author wqliu
 * @date 2021-08-21
 *
 */
@Service
public class ApiMessageTopicServiceImpl extends BaseServiceImpl<ApiMessageTopicMapper, ApiMessageTopic> implements ApiMessageTopicService {
    @Autowired
    private ApiMessagePermissionService apiMessagePermissionService;

    @Override
    public ApiMessageTopic init() {
        ApiMessageTopic entity = new ApiMessageTopic();
        entity.setStatus(StatusEnum.NORMAL.name());
        return entity;
    }

    @Override
    public void beforeAdd(ApiMessageTopic entity) {


        //验证编码全局唯一
        QueryWrapper<ApiMessageTopic> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApiMessageTopic::getCode, entity.getCode());
        int count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.CODE_EXIST);
        }


        //验证名称全局唯一
        queryWrapper.lambda().eq(ApiMessageTopic::getName, entity.getName());
        count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.NAME_EXIST);
        }


    }

    @Override
    public void beforeModify(ApiMessageTopic entity) {


        //验证编码全局唯一
        QueryWrapper<ApiMessageTopic> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApiMessageTopic::getCode, entity.getCode())
                .ne(ApiMessageTopic::getId, entity.getId());
        int count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.CODE_EXIST);
        }


        //验证名称全局唯一
        queryWrapper.lambda().eq(ApiMessageTopic::getName, entity.getName())
                .ne(ApiMessageTopic::getId, entity.getId());
        count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.NAME_EXIST);
        }


    }

    @Override
    public void enable(String id) {
        ApiMessageTopic entity = getEntity(id);
        entity.setStatus(StatusEnum.NORMAL.name());
        modify(entity);
    }

    @Override
    public void disable(String id) {
        ApiMessageTopic entity = getEntity(id);
        entity.setStatus(StatusEnum.DEAD.name());
        modify(entity);
    }

    @Override
    public List<ApiMessageTopic> queryMessageTopicPermission(QueryWrapper<ApiMessageTopic> queryWrapper, String appId,
                                                  String hasPermission) {
        //查询出所有接口服务
        List<ApiMessageTopic> serviceList = this.list(queryWrapper);
        //查询当前应用标识拥有权限的接口服务标识列表
        List<ApiMessagePermission> hasPermissionList =
                apiMessagePermissionService.lambdaQuery().eq(ApiMessagePermission::getAppId, appId).list();
        List<String> hasPermissionIdList = hasPermissionList.stream().map(x -> x.getMessageTopicId()).collect(Collectors.toList());
        //设置授权标志位
        serviceList.stream().forEach(x -> {
            if (CollectionUtils.isNotEmpty(hasPermissionIdList)) {
                //有至少1条权限记录
                if (hasPermissionIdList.contains(x.getId())) {
                    x.setHasPermission(YesOrNoEnum.YES.name());
                } else {
                    x.setHasPermission(YesOrNoEnum.NO.name());
                }
            } else {
                // 无任何权限，所有标识位置为NO
                x.setHasPermission(YesOrNoEnum.NO.name());
            }
        });
        if (StringUtils.isBlank(hasPermission)) {
            // 未设置查询条件，查询全部
            return serviceList;

        } else {
            //只查询对应的数据列表
            return serviceList.stream().filter(x -> x.getHasPermission().equals(hasPermission)).collect(Collectors.toList());
        }

    }

    @Override
    public String getHandlerByCode(String code) {
        ApiMessageTopic apiMessageTopic = getByCode(code);
        String handler =apiMessageTopic.getHandler();
        if(StringUtils.isBlank(handler)){
            throw new CustomException(ApiMessageTopicExceptionEnum.TOPIC_NOT_SET_HANDLER);
        }
        return handler;
    }

    @Override
    public String getSenderByCode(String code) {
        ApiMessageTopic apiMessageTopic = getByCode(code);
        String sender =apiMessageTopic.getSender();
        if(StringUtils.isBlank(sender)){
            throw new CustomException(ApiMessageTopicExceptionEnum.TOPIC_NOT_SET_SENDER);
        }
        return sender;
    }

    @Override
    public String getResponseTopicCodeByCode(String code) {
        List<ApiMessageTopic> list = this.lambdaQuery().eq(ApiMessageTopic::getCode, code).list();
        if(CollectionUtils.isEmpty(list)){
            throw new CustomException(ApiMessageTopicExceptionEnum.TOPIC_NOT_EXIST);
        }
        String responseTopicCode = list.get(0).getResponseTopicCode();
        if(StringUtils.isBlank(responseTopicCode)){
            throw new CustomException(ApiMessageTopicExceptionEnum.RESPONSE_TOPIC_NOT_SET_HANDLER);
        }
        return responseTopicCode;
    }

    @Override
    public String getIdByCode(String code) {
       return getByCode(code).getId();
    }

    @Override
    public ApiMessageTopic getByCode(String code) {
        List<ApiMessageTopic> list = this.lambdaQuery().eq(ApiMessageTopic::getCode, code).list();
        if(CollectionUtils.isNotEmpty(list)){
            return list.get(0);

        }else{
            throw new CustomException(ApiMessageTopicExceptionEnum.TOPIC_NOT_EXIST);
        }
    }
}